package main

import (
	"fmt"
	"strconv"
	"strings"
)

/*
给定一种规律pattern和一个字符串str，判断str是否遵循相同的规律。
这里的遵循指完全匹配，例如，pattern里的每个字母和字符串str中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
 */

func wordPattern(pattern string, str string) bool {
	// pattern = "abba", str = "dog cat cat dog"
	p := strings.Split(pattern,"") // [a b b a]
	s := strings.Split(str," ") // [dog cat cat dog]
	if len(p) != len(s) {
		return false
	}
	pNum,sNum := 0,0
	pString,sString := "",""
	pMap := map[string]int{}
	sMap := map[string]int{}
	for _,v := range p {
		if _,ok := pMap[v];ok{
			pString += strconv.Itoa(pMap[v])
		}else{
			pString += strconv.Itoa(pNum)
			pMap[v] = pNum
			pNum++
		}
	}
	for _,v := range s {
		if _,ok := sMap[v];ok{
			sString += strconv.Itoa(sMap[v])
		}else{
			sString += strconv.Itoa(sNum)
			sMap[v] = sNum
			sNum++
		}
	}
	if pString == sString {
		return true
	}
	return false
}

func main() {
	//str := "abba"
	//fmt.Println(str)
	//re := strings.Split(str, "")
	//fmt.Println(re)
	result := wordPattern("abba", "dog cat cat dog")
	fmt.Println(result)
}
